from fastapi import APIRouter, Depends, Request
from sqlalchemy.orm import Session
from app.database.database import get_db
from app.models.models import SysUser, SysMenu
from app.utils.auth import get_current_active_user
from app.utils.menu_utils import build_menu_tree
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse
import json

router = APIRouter()
templates = Jinja2Templates(directory="app/templates")

@router.get("/")
async def root(request: Request):
    # 重定向到admin页面
    return RedirectResponse(url="/admin")

# 页面路由 - 返回HTML页面
@router.get("/admin", response_class=HTMLResponse)
async def get_admin_page(request: Request):
    return templates.TemplateResponse("admin.html", {"request": request})

# API路由 - 返回JSON数据
@router.get("/api/user/info")
async def get_user_info(current_user: SysUser = Depends(get_current_active_user)):
    """获取当前登录用户信息"""
    return {
        "id": current_user.id,
        "name": current_user.name,
        "email": current_user.email,
        "is_admin": current_user.is_admin == 1,
        "is_active": current_user.is_active == 1
    }

@router.get("/api/user/is_admin")
async def get_user_is_admin(current_user: SysUser = Depends(get_current_active_user)):
    """获取当前用户是否是管理员"""
    return {"is_admin": current_user.is_admin == 1}

@router.get("/api/menus/user")
async def get_user_menus(current_user: SysUser = Depends(get_current_active_user), db: Session = Depends(get_db)):
    """获取当前用户可访问的菜单"""
    user_menus = []
    
    # 如果是管理员，获取所有菜单
    if current_user.is_admin == 1:
        menus = db.query(SysMenu).filter(SysMenu.is_active == 1).all()
        user_menus = menus
    # 否则获取用户有权限的菜单
    elif current_user.menu_json:
        try:
            menu_ids = json.loads(current_user.menu_json)
            user_menus = db.query(SysMenu).filter(SysMenu.id.in_(menu_ids)).filter(SysMenu.is_active == 1).all()
        except:
            user_menus = []
    
    # 构建菜单树
    menu_tree = build_menu_tree(user_menus)
    
    return {"menu_tree": menu_tree} 